package com.godtree.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
@WebFilter(filterName="TomcatFormFilter",urlPatterns={"/*"})
public class TomcatFormFilter implements Filter {
 public void destroy() {
  // TODO Auto-generated method stub
 
 }

 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
  // 1. ServletRequest 转成 HttpServletRequest
  HttpServletRequest req = (HttpServletRequest)request;
 
  // 2. 如果是GET，就生成一个Wrapper对象，覆盖获取参数的方法进行转码
  if("GET".equalsIgnoreCase(req.getMethod())) {
   req = new MyRequest(req);
  }
  // 3. 如果是POST，request.setCharacterEncoding("UTF-8")
  else if("POST".equalsIgnoreCase(req.getMethod())) {
   req.setCharacterEncoding("UTF-8");
  }
  // 4.调用chain.doFilter继续向后执行
  chain.doFilter(req, response);
 }

 public void init(FilterConfig arg0) throws ServletException {
  // TODO Auto-generated method stub
 
 }

}